var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js');
var user = require('../db/userSql.js');
var QcloudSms = require("qcloudsms_js");
let jwt = require('jsonwebtoken');
//支付宝
const alipaySdk = require('../db/alipay.js');
const AlipayFormData = require('alipay-sdk/lib/form').default;
//引入axios
const axios = require('axios');
//后端设置跨域？
// router.all('*', function (req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*');
//   //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
//   res.header('Access-Control-Allow-Headers', 'Content-Type');
//   res.header('Access-Control-Allow-Methods', '*');
//   res.header('Content-Type', 'application/json;charset=utf-8');
//   next();
// });


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
//支付状态
router.post('/api/paymentSuccess',function(req,res,next){
    
    //订单号
    let out_trade_no = req.body.out_trade_no;
    //支付宝流水号
    let trade_no = req.body.trade_no;
    
    //支付宝配置 : 后端要和支付宝方进行对接，支付宝方告诉后端，是否支付成功|失败
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    formData.addField('bizContent', {
        out_trade_no,
        trade_no
    });
    //写死的
    const result = alipaySdk.exec(
      'alipay.trade.query',
      {},
      { formData: formData },
    );
    //后端去请求支付宝
    result.then(resData=>{
        axios({
            url:resData,
            method:'GET'
        }).then(data=>{
            let response = data.data.alipay_trade_query_response;
            //用户去支付
            if( response.code == 10000  ){
                
                switch(  response.trade_status  ){
                    case 'WAIT_BUYER_PAY':
                        res.send({
                            data:{
                                code:0,
                                msg:'支付宝有交易记录，没付款'
                            }
                        })
                    break;
                    
                    case 'TRADE_CLOSED':
                        res.send({
                            data:{
                                code:0,
                                msg:'交易关闭，没付款'
                            }
                        })
                    break;
                    
                    case 'TRADE_FINISHED':
                        res.send({
                            data:{
                                code:1,
                                msg:'交易完成'
                            }
                        })
                    break;
                    
                    case 'TRADE_SUCCESS':
                        res.send({
                            data:{
                                code:1,
                                msg:'交易完成'
                            }
                        })
                    break;
                    
                }
                
            }else if(  response.code == 40004  ){
                res.send({
                    data:{
                        code:500,
                        msg:'交易不存在'
                    }
                })
            }
        }).catch(err=>{
            res.send({
                data:{
                    code:500,
                    msg:'交易失败'
                }
            })
        })
    })
})
//去支付==》对接支付宝沙箱
router.post('/api/payment',function(req,res,next){
    //拿到前端给后端传递的数据
    //订单号
    let orderId = req.body.orderId;
    //总价
    let price = req.body.price;
    //名称
    let name = req.body.name;
    //支付宝sdk代码
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    formData.addField('bizContent', {
        //订单号
        outTradeNo: orderId,
        //写死
        productCode: 'FAST_INSTANT_TRADE_PAY',
        totalAmount: price,
        subject: name,
    });
    //支付成功或者失败跳转的url
    formData.addField('returnUrl', 'http://localhost:8080/success');
    //写死的
    const result = alipaySdk.exec(
      'alipay.trade.page.pay',
      {},
      { formData: formData },
    );
    
    result.then(resp=>{
       res.send({
           data:{
               succees:true,
               msg:'支付中...',
               url:resp
           }
       })
    })
})

//修改订单状态和删除购物车数据
router.post('/api/submitOrder',function(req,res,next){
    //获取token
    let token = req.headers.token;
    let tokenObj = jwt.decode( token );
    //订单号
    let orderId = req.body.orderId;
    //选中商品的id号，是一个数组shopArr
    let shopArr = req.body.shopArr;
    //查询用户
    connection.query(`select * from user where tel=${tokenObj.name}`,function(error,results){
        //当前登录用户的id号
        let userId = results[0].id;
        //查询订单
        connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(err,result){
            //在数据库中，订单的id
            let id = result[0].id;
            //修改订单的状态
            connection.query(`update store_order set order_status = replace(order_status,'1','2') where id = ${id}`,function(e,r){
                //删除购物车的数据
                shopArr.forEach(v=>{
                    connection.query(`delete from goods_cart where id = ${v}`,function(){
                    })
                })
                res.send({
                    data:{
                        code:200,
                        succees:true
                    }
                })
            })
        })
    })
})
//查询订单
router.post('/api/selectOrder',function(req,res,next){
    let orderId = req.body.orderId;
    connection.query(`select * from store_order where order_id = ${orderId} and order_status = '1'`,function(error,results){
        res.send({
            data:{
                code:200,
                success:true,
                data:results
            }
        })
    })
})

//生成订单
router.post('/api/addOrder',function(req,res,next){
    //获取token
    let token = req.headers.token;
    let tokenObj = jwt.decode( token );
    //前端给后端的数据
    let goodsArr = req.body.arr;
    //订单号的规则 ==》 时间 + 6位随机数
    function randomNumber(){
        const now = new Date();
        let fullyear = now.getFullYear();
        let month = now.getMonth() + 1;
        let day = now.getDate();
        let hours = now.getHours();
        let minutes = now.getMinutes();
        let seconds = now.getSeconds();
        
        month = month.toString().padStart(2,'0');
        day = day.toString().padStart(2,'0');
        hours = hours.toString().padStart(2,'0');
        minutes = minutes.toString().padStart(2,'0');
        seconds = seconds.toString().padStart(2,'0');
        
        let orderCode = fullyear.toString() + month + day + hours + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
        return orderCode;
    }
    
    //商品名称
    let goodsName = [];
    //订单商品的总价格
    let goodsPrice = 0;
    //订单商品的总数量
    let goodsNum = 0;
    //订单号
    let orderId = randomNumber();
    
    goodsArr.forEach(v=>{
        goodsName.push( v.goods_name );
        goodsNum += parseInt( v.goods_num );
        goodsPrice += v.goods_num * v.goods_price;
    })
    
    connection.query( `select * from user where tel=${tokenObj.name}`,function(error,results){
        //当前登录用户的id号
        let userId = results[0].id;
        connection.query(`insert into store_order (uId,order_id,goods_name,goods_num,goods_price,order_status) values (${userId},'${ orderId }','${goodsName}','${ goodsNum }','${goodsPrice}','1')`,function(){
            connection.query(`select * from store_order where uId=${userId} and order_id = ${orderId}`,function(err,result){
                res.send({
                    data:{
                        success:true,
                        code:200,
                        data:result
                    }
                })
            })
        }) 
    })
})
//修改收货地址
router.post('/api/updateAddress',function(req,res,next){
    //前端给后端的数据
    let body = req.body;
    let [id,name,tel,province,city,county,addressDetail,areaCode,isDefault] = [
        body.id,
        body.name,
        body.tel,
        body.province,
        body.city,
        body.county,
        body.addressDetail,
        body.areaCode,
        body.isDefault
    ];
    //获取token
    let token = req.headers.token;
    let tokenObj = jwt.decode( token );
    connection.query( `select * from user where tel=${tokenObj.name}`,function(error,results){
        //当前登录用户的id号
        let userId = results[0].id;
        //查询之前有没有默认收货地址：1
        connection.query(`select * from address where uId = ${userId} and isDefault = 1`,function(err,result){
            let updateSql = `update address set uId = ? , name = ? , tel = ? , province = ? , city = ? , county = ? , addressDetail = ? , areaCode = ? , isDefault = ? where id = ${id}`;
            //之前没有默认收货地址（1）
            if( result.length ){
                //查询到之前，是默认收货地址的id号
                let isDefaultId = result[0].id;
                if( isDefault == 1 ){
                    connection.query(`update address set isDefault = replace(isDefault,'1','0') where id = ${isDefaultId}`,function(e,r){
                        connection.query(updateSql,[userId,name,tel,province,city,county,addressDetail,areaCode,isDefault],function(){
                            res.send({
                                data:{
                                    code:200,
                                    success:true,
                                    msg:'修改成功'
                                }
                            })
                        })
                    })
                }else{
                    connection.query(updateSql,[userId,name,tel,province,city,county,addressDetail,areaCode,isDefault],function(e,r){
                        res.send({
                            data:{
                                code:200,
                                success:true,
                                msg:'修改成功'
                            }
                        })
                    })
                }
                
            }else{
            //之前没有默认收货地址（1）
                connection.query(updateSql,[userId,name,tel,province,city,county,addressDetail,areaCode,isDefault],function(e,r){
                    res.send({
                        data:{
                            code:200,
                            success:true,
                            msg:'修改成功'
                        }
                    })
                })
            }
        })
        
    })
    
})
//删除收货地址
router.post('/api/deleteAddress',function(req,res,next){
    
    let id = req.body.id;
    connection.query(`delete from address where id = ${id}`,function(error,results){
        res.send({
            data:{
                code:200,
                success:true,
                msg:'删除成功'
            }
        })
    })
})
//查询收货地址
router.post('/api/selectAddress',function(req,res,next){
    //获取token
    let token = req.headers.token;
    let tokenObj = jwt.decode( token );
    connection.query(`select * from user where tel=${tokenObj.name}`,function(error,results){
        //当前登录用户的id号
        let id = results[0].id;
        connection.query(`select * from address where uId = ${id}`,function(err,result){
            res.send({
                data:{
                    code:200,
                    success:true,
                    data:result
                }
            })
        })
   
    })
})
//新增收货地址
router.post('/api/addAddress',function(req,res,next){
    //前端给后端的数据
    let body = req.body;
    let [name,tel,province,city,county,addressDetail,areaCode,isDefault] = [
        body.name,
        body.tel,
        body.province,
        body.city,
        body.county,
        body.addressDetail,
        body.areaCode,
        body.isDefault
    ];
    //获取token
    let token = req.headers.token;
    let tokenObj = jwt.decode( token );
    connection.query( `select * from user where tel=${tokenObj.name}`,function(error,results){
        //当前登录用户的id号
        let id = results[0].id;
        if( isDefault != 1 ){
            connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,areaCode,isDefault) values (${id},'${name}','${tel}','${province}','${city}','${county}','${addressDetail}','${areaCode}','${isDefault}')`,function(error,result){
                res.send({
                    data:{
                        msg:'添加成功',
                        code:200,
                        success:true
                    }
                })
            })
        }else{
            //查询address表的当前用户的isDefault字段=1的 这条记录
            connection.query(`select * from address where uId = ${id} and isDefault = ${isDefault}`,function(err,result){
                //之前有默认收货地址
                if( result.length  ){
                    //修改操作 
                    let addressId = result[0].id;
                    //修改完成
                    connection.query(`update address set isDefault = replace(isDefault,'1','0') where id = ${addressId}`,function(e,r){
                        //增加数据
                        connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,areaCode,isDefault) values (${id},'${name}','${tel}','${province}','${city}','${county}','${addressDetail}','${areaCode}','${isDefault}')`,function(error,result){
                            res.send({
                                data:{
                                    msg:'添加成功',
                                    code:200,
                                    success:true
                                }
                            })
                        })
                    })
                }else{
                //之前没有默认收货地址
                    connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,areaCode,isDefault) values (${id},'${name}','${tel}','${province}','${city}','${county}','${addressDetail}','${areaCode}','${isDefault}')`,function(error,result){
                        res.send({
                            data:{
                                msg:'添加成功',
                                code:200,
                                success:true
                            }
                        })
                    })
                }
            })
        }
    })
})

//修改购物车数据
router.post('/api/updateCart',function(req,res,next){
    //购物车的数据id
    let id = req.body.id;
    //修改后的数据
    let changeNum = req.body.changeNum;
    //查询有没有这条记录（数据）
    connection.query(`select * from goods_cart where id = ${id}`,function(error,results){
        //原来记录的数量
        let num = results[0].goods_num;
        connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${changeNum}) where id = ${id}`,function(err,result){
            res.send({
                data:{
                    code:200,
                    success:true,
                    msg:'修改成功'
                }
            })
        })
    })
})
//删除购物车数据
router.post('/api/deleteCart',function(req,res,next){
    let arrId = req.body.arrId
    for(let i=0;i<arrId.length;i++){
        connection.query(`delete from goods_cart where id = ${arrId[i]}`,function(error,results){
            res.send({
                data:{
                    code:200,
                    success:true,
                    msg:"删除成功"
                }
            })
        })
    }
})
//查询购物车数据
router.post('/api/selectCart',function(req,res,next){
    //获取token
    let token = req.headers.token;
    let tokenObj = jwt.decode( token );
    connection.query( `select * from user where tel=${tokenObj.name}`,function(error,results){
        let id = results[0].id;
        connection.query(`select * from goods_cart where uId = ${id}`,function(err,result){
            res.send({
                data:{
                    code:200,
                    data:result
                }
            })
        })
    })
})

function getTimeToken( exp ){
    //当前时间
    let getTimes = parseInt( new Date().getTime() / 1000 );
    if( getTimes - exp > 60 ){
        return true;
    }
}

//加入购物车==》新增购物车数据
router.post('/api/addCart',function(req,res,next){
    //获取token
    let token = req.headers.token;
    let tokenObj = jwt.decode( token );
    //商品id
    let goodId = req.body.goodsId;
    
   
    //token过期了
    if( getTimeToken(tokenObj.exp) ){
        res.send({
            data:{
                code:1000
            }
        })
    }
    
    connection.query( `select * from user where tel=${tokenObj.name}`,function(error,results){
        //用户的id
        let id = results[0].id;
        //查询商品
        connection.query(`select * from goods_list where id = ${goodId}`,function(err,result){
            //商品名称
            let goods_name = result[0].goods_name;
            //商品价格
            let goods_price = result[0].goods_price;
            //商品图片
            let goods_imgUrl = result[0].goods_imgUrl;
            //查询目前的数据库有没有这条记录
            connection.query(`select * from goods_cart where uId = ${id} and goods_id = ${result[0].id}`,function(e,r){
                //已经有
                if( r.length > 0 ){
                    //旧的数量
                    let oldNum = r[0].goods_num;
                    connection.query(`update goods_cart set goods_num = replace(goods_num,${oldNum},${ parseInt(oldNum) + 1 }) where id = ${r[0].id}`,function(){
                        res.send({
                            data:{
                                code:200,
                                success:true,
                                msg:'加入购物车成功'
                            }
                        })
                    })
                }else{
                    //如果没有就新增一条
                    connection.query(`insert into goods_cart (uId,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values(${id},${goodId},"${goods_name}","${goods_price}","1","${goods_imgUrl}")`,function(){
                        res.send({
                            data:{
                                code:200,
                                success:true,
                                msg:'加入购物车成功'
                            }
                        })
                    })
                }
                
            })
        })
    })
})
//根据id号，查询对应的商品
router.get('/api/details',function(req,res,next){
    //商品的id号
    let id = req.query.id;
    //查询语句
    connection.query(`select * from goods_list where id=${id}`,function(error,result){
        res.send({
            data:{
                code:200,
                success:true,
                data:result[0]
            }
        })
    })
})

//找回密码
router.post('/api/recovery',function(req,res,next){
    //后端要接收前端发过来的参数
    let params = req.body;
    //查询用户存在不存在
    connection.query(   user.queryUserTel( params )  ,function( error, results ){
        //数据库用户的id
        let id = results[0].id;
        //数据库用户的  老 密码
        let pwd = results[0].pwd;
        //修改用户密码  ==> replace(字段,旧密码,新密码)
        connection.query(`update user set pwd = replace(pwd,${pwd},${params.pwd}) where id = ${id}`,function(err,result){
            res.send({
                data:{
                    code:200,
                    success:true,
                    msg:'修改成功'
                }
            })
        })   
    })
})
//注册
router.post('/api/register',function(req,res,next){
    //前端给后端的数据
    let paramsVal = req.body;
    //查询用户是否已经注册
    connection.query(   user.queryUserTel( paramsVal )  ,function( error, results ){
        
        if( results.length > 0 ){
        //如果大于0，这个用户是存在的
            res.send({
                data:{
                    code:200,
                    success:false,
                    msg:'该用户已经注册过了，请登录'
                }
            })
        }else{
        //该用户没有注册过
            connection.query( user.insertUser(paramsVal),function(err,result){
                
                connection.query(   user.queryUserTel( paramsVal )  ,function( e, r ){
                    res.send({
                        data:{
                            code:200,
                            success:true,
                            msg:'注册成功，正在登录...',
                            data:r[0]
                        }
                    })
                })
                
            })
        }
        
    })
    
})

//查询用户
router.post('/api/selectUser',function(req,res,next){
    //后端要接收前端发过来的参数
    let params = req.body;
    connection.query(   user.queryUserTel( params )  ,function( error, results ){
        if( results.length > 0 ){
        //有这个手机号    
            res.send({
                data:{
                    code:200,
                    success:true,
                    data:{
                        id:results[0].id,
                        imgUrl: results[0].imgUrl,
                        nickName: results[0].nickName,
                        token: results[0].token
                    }
                }
            })
        }else{
        //没有此用户
            res.send({
                data:{
                    code:300,
                    success:false,
                    msg:'手机号不存在'
                }
            })
        }
    })
});


//对接短信验证码
router.post('/api/code',function(req,res,next){
    
    let tel = req.body.tel;
    //腾讯云短信的配置
    // 短信应用SDK AppID
    var appid = 1400187558;  // SDK AppID是1400开头
    
    // 短信应用SDK AppKey
    var appkey = "dc9dc3391896235ddc2325685047edc7";
    
    // 需要发送短信的手机号码
    var phoneNumbers = [tel];
    
    // 短信模板ID，需要在短信应用中申请
    var templateId = 285590;  // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请
    
    // 签名
    var smsSign = "三人行慕课";  // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`
    
    // 实例化QcloudSms
    var qcloudsms = QcloudSms(appid, appkey);
    
    // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
    function callback(err, ress, resData) {
        if (err) {
            console.log("err: ", err);
        } else {
           res.send({
               data:{
                   code:200,
                   success:true,
                   data:ress.req.body.params[0]
               }
           })
        }
    }
    
    var ssender = qcloudsms.SmsSingleSender();
    //就是给手机上发送的短信验证
    var params = [  Math.floor( Math.random() * (9999-1000))+1000 ];
    ssender.sendWithParam(86, phoneNumbers[0], templateId,
      params, smsSign, "", "", callback);  // 签名参数不能为空串
    
})
//登录
router.post('/api/login',function(req,res,next){
    //后端要接收前端发过来的参数
    let params = req.body;
    
    let tel = params.tel;
    let pwd = params.pwd;
    let jwt = require('jsonwebtoken');
    
    let token = jwt.sign({
        name:tel
    },'xiaoluxian',{
        expiresIn:60
    });
    
    connection.query( user.queryUserTel( params )  ,function( error, results ){
        if( results.length > 0 ){
        //有这个手机号    
             connection.query(   user.queryUserPwd( params )  ,function( err, result ){
                let id = result[0].id;
                if( result.length > 0  ){
                    
                    connection.query(`update user set token = '${token}' where id = ${id}`,function(){
                        //全对
                        res.send({
                            data:{
                                code:200,
                                success:true,
                                msg:'登录成功',
                                data:result[0]
                            }
                        })
                    })
                }else{
                //密码不正确
                    res.send({
                        data:{
                            code:300,
                            success:false,
                            msg:'密码不对'
                        }
                    })
                }
                
             })
            
        }else{
        //没有此用户
            res.send({
                data:{
                    code:300,
                    success:false,
                    msg:'手机号不存在'
                }
            })
        }
            
    })
    
});
//分类数据
router.get('/api/list',function(req,res,next){
	res.send({
		data:[
			//一级
			{
				id:0,
				name:'推荐',
				data:[
					//二级
					{
						id:0,
                        name:'推荐',
                        data:[
                            //三级
                            {
                                id:0,
                                name:'铁观音',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:1,
                                name:'龙井',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:2,
                                name:'功夫茶具',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:3,
                                name:'紫砂壶',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:4,
                                name:'绿茶',
                                imgUrl:'/images/list1.jpeg'
                            }
                        ]
					}
				]
			},
			{
				id:0,
				name:'绿茶',
				data:[
					//二级
					{
						id:0,
			            name:'绿茶',
			            data:[
			                //三级
			                {
			                    id:0,
			                    name:'龙井',
			                    imgUrl:'/images/list1.jpeg'
			                },
			                {
			                    id:1,
			                    name:'毛峰',
			                    imgUrl:'/images/list1.jpeg'
			                },
			                {
			                    id:2,
			                    name:'碧螺春',
			                    imgUrl:'/images/list1.jpeg'
			                },
			                {
			                    id:3,
			                    name:'白茶',
			                    imgUrl:'/images/list1.jpeg'
			                },
			                {
			                    id:4,
			                    name:'瓜片',
			                    imgUrl:'/images/list1.jpeg'
			                },
                            {
                                id:5,
                                name:'猴魁',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:6,
                                name:'雀舌',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:7,
                                name:'随便',
                                imgUrl:'/images/list1.jpeg'
                            }
			            ]
					}
				]
			},
			{
				id:0,
				name:'乌龙',
				data:[
					//二级
					{
						id:0,
			            name:'乌龙',
			            data:[
			                //三级
			                {
			                    id:0,
			                    name:'龙井',
			                    imgUrl:'/images/list1.jpeg'
			                },
			                {
			                    id:1,
			                    name:'毛峰',
			                    imgUrl:'/images/list1.jpeg'
			                },
			                {
			                    id:2,
			                    name:'碧螺春',
			                    imgUrl:'/images/list1.jpeg'
			                }
			            ]
					}
				]
			},
            {
            	id:0,
            	name:'红茶',
            	data:[
            		//二级
            		{
            			id:0,
                        name:'红茶',
                        data:[
                            //三级
                            {
                                id:0,
                                name:'龙井',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:1,
                                name:'毛峰',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:2,
                                name:'碧螺春',
                                imgUrl:'/images/list1.jpeg'
                            }
                        ]
            		}
            	]
            },
            {
            	id:0,
            	name:'白茶',
            	data:[
            		//二级
            		{
            			id:0,
                        name:'白茶',
                        data:[
                            //三级
                            {
                                id:0,
                                name:'龙井',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:1,
                                name:'毛峰',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:2,
                                name:'碧螺春',
                                imgUrl:'/images/list1.jpeg'
                            }
                        ]
            		}
            	]
            },
            {
            	id:0,
            	name:'普洱',
            	data:[
            		//二级
            		{
            			id:0,
                        name:'普洱',
                        data:[
                            //三级
                            {
                                id:0,
                                name:'龙井',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:1,
                                name:'毛峰',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:2,
                                name:'碧螺春',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:3,
                                name:'白茶',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:4,
                                name:'瓜片',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:5,
                                name:'猴魁',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:6,
                                name:'雀舌',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:7,
                                name:'随便',
                                imgUrl:'/images/list1.jpeg'
                            }
                        ]
            		}
            	]
            },
            {
            	id:0,
            	name:'花茶',
            	data:[
            		//二级
            		{
            			id:0,
                        name:'花茶',
                        data:[
                            //三级
                            {
                                id:0,
                                name:'龙井',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:1,
                                name:'毛峰',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:2,
                                name:'碧螺春',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:3,
                                name:'白茶',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:4,
                                name:'瓜片',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:5,
                                name:'猴魁',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:6,
                                name:'雀舌',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:7,
                                name:'随便',
                                imgUrl:'/images/list1.jpeg'
                            }
                        ]
            		}
            	]
            },
            {
            	id:0,
            	name:'茶具',
            	data:[
            		//二级
            		{
            			id:0,
                        name:'茶具',
                        data:[
                            //三级
                            {
                                id:0,
                                name:'龙井',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:1,
                                name:'毛峰',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:2,
                                name:'碧螺春',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:3,
                                name:'白茶',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:4,
                                name:'瓜片',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:5,
                                name:'猴魁',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:6,
                                name:'雀舌',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:7,
                                name:'随便',
                                imgUrl:'/images/list1.jpeg'
                            }
                        ]
            		}
            	]
            },
            {
            	id:0,
            	name:'手艺',
            	data:[
            		//二级
            		{
            			id:0,
                        name:'手艺',
                        data:[
                            //三级
                            {
                                id:0,
                                name:'龙井',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:1,
                                name:'毛峰',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:2,
                                name:'碧螺春',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:3,
                                name:'白茶',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:4,
                                name:'瓜片',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:5,
                                name:'猴魁',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:6,
                                name:'雀舌',
                                imgUrl:'/images/list1.jpeg'
                            },
                            {
                                id:7,
                                name:'随便',
                                imgUrl:'/images/list1.jpeg'
                            }
                        ]
            		}
            	]
            }
		]
	})
	
})

//查询商品
router.get('/api/goodsList',function(req,res,next){
	//后端接收到前端的数据
	let [key,name] =  Object.keys(  req.query  );
	
	let [keyName,order] = Object.values( req.query  );
	
	//执行sql语句
	connection.query('select * from goods_list where goods_name like "%'+keyName+'%" order by '+name+' '+order+'',function(error,result){
		//后端给前端返回的数据
		res.send({
			code:200,
			data:{
				result
			}
		})
	})
})

//首页 ===> 推荐的 1 数据
router.get('/api/index_list/0/data/1',function(req,res,next){
	
	res.send({
		code:0,
		data:{
			topBar:[
				{id:0,label: '推荐'},
				{id:1,label: '大红袍'},
				{id:2,label: '铁观音'},
				{id:3,label: '绿茶'},
				{id:4,label: '红茶'},
				{id:5,label: '茶具'},
				{id:6,label: '黑茶'}
			],
			data:[
				{
					id:0,
					type:'swiperList',
					data:[
						{id:0,imgUrl:'./images/swiper1.jpeg'},
						{id:1,imgUrl:'./images/swiper2.jpeg'}
					]
				},
				{
					id:1,
					type:'iconsList',
					data:[
						{
							id:0,
							title:'自饮茶',
							imgUrl:'./images/icons1.png',
						},
						{
							id:1,
							title:'茶具',
							imgUrl:'./images/icons2.png',
						},
						{
							id:2,
							title:'茶礼盒',
							imgUrl:'./images/icons3.png',
						},
						{
							id:3,
							title:'领福利',
							imgUrl:'./images/icons4.png',
						},
						{
							id:4,
							title:'官方验证',
							imgUrl:'./images/icons5.png',
						}
					]
				},
				{
					id:2,
					type:'likeList',
					data:[
						{
							id:1,
							title:'浓香铁观音 1号500g 消青工艺',
							price:'299',
							imgUrl:'./images/like1.jpeg'
						},
						{
							id:2,
							title:'高级岩茶 武夷山原产地大红袍 2号160g',
							price:'2',
							imgUrl:'./images/like1.jpeg',
						},
						{
							id:3,
							title:'浓香铁观音 1号500g 消青工艺',
							price:'299',
							imgUrl:'./images/like1.jpeg'
						},
						{
							id:4,
							title:'高级岩茶 武夷山原产地大红袍 2号160g',
							price:'2',
							imgUrl:'./images/like1.jpeg',
						},
						{
							id:5,
							title:'高级岩茶 武夷山原产地大红袍 2号160g',
							price:'2',
							imgUrl:'./images/like2.jpeg',
						},
						{
							id:6,
							title:'高级岩茶 武夷山原产地大红袍 2号160g',
							price:'2',
							imgUrl:'./images/like2.jpeg',
						},
						{
							id:7,
							title:'高级岩茶 武夷山原产地大红袍 2号160g',
							price:'2',
							imgUrl:'./images/like3.jpeg',
						},
						{
							id:8,
							title:'高级岩茶 武夷山原产地大红袍 2号160g',
							price:'2',
							imgUrl:'./images/like3.jpeg',
						}
					]
				}
			]
		}
	})

})

//首页 ===> 大红袍的 1 数据
router.get('/api/index_list/1/data/1',function(req,res,next){
	
	res.send({
		code:0,
		data:[
			{
				id:0,
				type:'iconsList',
				data:[
					{
						id:0,
						title:'自饮茶',
						imgUrl:'./images/icons1.png',
					},
					{
						id:1,
						title:'茶具',
						imgUrl:'./images/icons2.png',
					},
					{
						id:2,
						title:'茶礼盒',
						imgUrl:'./images/icons3.png',
					},
					{
						id:3,
						title:'领福利',
						imgUrl:'./images/icons4.png',
					},
					{
						id:4,
						title:'官方验证',
						imgUrl:'./images/icons5.png',
					}
				]
			}
		]
	})
	
})
//首页 ===> 铁观音的 1 数据
router.get('/api/index_list/2/data/1',function(req,res,next){
	
	res.send({
		code:0,
		data:[
			{
				id:0,
				type:'swiperList',
				data:[
					{id:0,imgUrl:'./images/swiper1.jpeg'},
					{id:1,imgUrl:'./images/swiper2.jpeg'}
				]
			}
		]
	})

})

module.exports = router;
